package com.landmark;

import java.awt.EventQueue;
import java.io.FileWriter;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class FameFabricsCat extends SwingWorker<Boolean, Boolean> {

    FileWriter fw = null;
    FileWriter errorFile = null;
    int pageNo;
    StringBuffer sb = new StringBuffer();
    Hashtable<String, String> htModelLinks = new Hashtable<String, String>();
    String status = "";
    JTextArea txtArea;
    UMProgressBar pBar = null;
    int lineCount = 0;

    @Override
    protected Boolean doInBackground() throws Exception {
        start();
        return true;
    }

    @Override
    protected void done() {
        Util.taskCompleteMsg(status);
    }

    public void start() {
        try {
            String dirName = "./outputs";
            String imagesPath = "./outputs/FameFabricsImages";
            String swatchesPath = "./outputs/FameFabricsSwatches";


            Util.createDirectory(dirName);
            Util.createDirectory(imagesPath);
            Util.createDirectory(swatchesPath);

            txtArea = Util.createOutputFile("FameFabrics");
            HelperBean helperBean = Util.getHelperBean();

            fw = new FileWriter(helperBean.getOutputFile());
            errorFile = new FileWriter(helperBean.getErrorFile());
            String[] catIds = {"46645", "46646", "46647", "46648", "45473"};
            // Here we get all the search pages from page 0 to 9 which we know by seeing the site
            for (pageNo = 0; pageNo < catIds.length; pageNo++) {
                if (Util.getHelperBean().isTerminateCurrentProcess()) {
                    break;
                }
                String str = "http://www.chefdesigns.com/product2/objectviewer.aspx?Type=Category&ObjectID=" + catIds[pageNo];
                txtArea.setText(str);
                txtArea.paintImmediately(txtArea.getVisibleRect());
                processCategoryPage(str);
            }

            txtArea.append("\nFiles are located at : \n" + helperBean.getOutputFile().getAbsolutePath() + "\n" + helperBean.getErrorFile().getAbsolutePath() + "\n");
            txtArea.append("Total products : " + htModelLinks.size() + "\n");
            txtArea.paintImmediately(txtArea.getVisibleRect());
            Util.getHelperBean().setLineCount(htModelLinks.size());

            iterateCollection(htModelLinks);

            if (fw != null) {
                fw.close();
            }

        } catch (Exception e) {
            status = e.getLocalizedMessage();
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (Exception e1) {
                // TODO: handle exception
            }
        }
        status = status.trim().equals("") ? "Done processing." : status;
        if (Util.getHelperBean().isTerminateCurrentProcess()) {
            status = "Process Terminated";
        }
        txtArea.append("\n" + status);
    }

    /**
     *
     * @param htLinks
     */
    private void iterateCollection(Hashtable<String, String> htLinks) {
        try {
            lineCount = 0;
            pBar = new UMProgressBar();
            Enumeration<String> keys = htLinks.keys();
            fw.write("Product_Id, Product_Name, Category_Structure,Product_Image_URL\n");
            while (keys.hasMoreElements()) {
                if (Util.getHelperBean().isTerminateCurrentProcess()) {
                    break;
                }
                String key = (String) keys.nextElement();
                txtArea.append("Processing page: " + key + "\n");
                txtArea.paintImmediately(txtArea.getVisibleRect());
                sb = new StringBuffer();
                Util.getHelperBean().setCurrentCount(lineCount++);

                processModels(htLinks.get(key).toString());
                fw.write(sb.toString().replaceAll("\n", "").replace("   ", "").replaceAll("<#NEWLINE#>", "\n"));
                fw.write("\n");
                fw.flush();
                if (Util.getHelperBean().getLineCount() == lineCount) {
                    Util.getHelperBean().setProcessingDone(true);
                    pBar.close();
                }
                EventQueue.invokeLater(pBar);
            }
        } catch (Exception e) {
        }
    }

    /**
     *
     * @param aUrl
     */
    private void processModels(String aUrl) throws Exception {
        try {
            Util.getParserFromUrl(aUrl, null);

            String prdtIdLs = Util.getHelperBean().getInputHTML().select("span#Render1__ctl2_lblObjectTitleText").text();

            String prdtcatStructure = Util.getHelperBean().getInputHTML().select(".Breadcrumbs").text();

            Elements prdtDescLs = Util.getHelperBean().getInputHTML().select("td[width=80%]");
            StringBuilder prdtDesc = new StringBuilder();
            for (Element ele : prdtDescLs) {
                prdtDesc.append(ele.text()).append("</li><li>");
            }
            sb.append(prdtIdLs);
            sb.append(",");
            sb.append(prdtDesc.toString().replaceAll(",", "&#044;"));
            sb.append(",");
            sb.append(prdtcatStructure);
            sb.append(",");

            Elements prdtImages = Util.getHelperBean().getInputHTML().select("#Render1__ctl2_imgObjectImage").select("img[src$=.jpg]");
//            //Elements prdtSwatches = Util.getHelperBean().getInputHTML().select(".colors").select("img[src$=.jpg]");
//            // gets all the main images
            for (Element ele : prdtImages) {
                //System.out.println(ele.absUrl("src"));
                String imageUrl = ele.absUrl("src");
                String imageName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1, imageUrl.lastIndexOf("."));

                String baseImageUri = "http://www.chefdesigns.com/product2/ModalControls/ShowZoom.aspx?ImageName=";
                String prdtId = aUrl.substring(aUrl.lastIndexOf("=") + 1, aUrl.length());
                imageUrl = baseImageUri + imageName + ".tif&ObjectID=" + prdtId + "&ImageType=4";

                sb.append(ele.absUrl("src"));
                sb.append("<#NEWLINE#>");
                Util.saveImage(imageUrl, "./outputs/ChefDesignImages", "ImageName");
            }
            // gets all the swatches
//            for (Element ele : prdtSwatches) {                
//                String src = URLEncoder.encode(ele.absUrl("src"));
//                                
//                src = URLDecoder.decode(src.replaceAll("5C", "2F"));
//                Util.saveImage(src, "./outputs/ChefDesignSwatches");
//            }
        } catch (SocketTimeoutException e) {
            try {
                processModels(aUrl);
            } catch (Exception e1) {
            }
        } catch (ConnectException e) {
            try {
                processModels(aUrl);
            } catch (Exception e1) {
            }
        }
    }

    private void processCategoryPage(String aUrl) throws Exception {
        try {
            Document doc = Jsoup.connect(aUrl).get();
            Elements elements = doc.select(".categoryLinkTitle").select("a[href]");
            System.out.println(elements.size());
            for (Element element : elements) {
                String absoluteUrl = element.attr("abs:href");
                processCategoryResultsPage(absoluteUrl);
            }
        } catch (SocketTimeoutException e) {
            try {
                processCategoryPage(aUrl);
            } catch (Exception e1) {
            }
        } catch (ConnectException e) {
            try {
                processCategoryPage(aUrl);
            } catch (Exception e1) {
            }
        }
    }

    private void processCategoryResultsPage(String aUrl) throws Exception {
        try {
            Document doc = Jsoup.connect(aUrl.replaceAll(" ", "+")).get();
            Elements elements = doc.select(".ObjectItemGrid").select("a[href]");
            for (Element element : elements) {
                String absoluteUrl = element.attr("abs:href");
                htModelLinks.put(absoluteUrl, absoluteUrl);
//                if( htModelLinks.size() > 5 ) break;
            }
        } catch (SocketTimeoutException e) {
            try {
                processCategoryResultsPage(aUrl);
            } catch (Exception e1) {
            }
        } catch (ConnectException e) {
            try {
                processCategoryResultsPage(aUrl);
            } catch (Exception e1) {
            }
        }
    }
}
